package org.example.demo.config;

import com.rabbitmq.client.Channel;
import org.example.demo.common.serializer.Serializer;
import org.example.demo.common.serializer.SerializerFactory;
import org.example.demo.common.serializer.SerializerVariety;
import org.example.demo.common.serializer.impl.SerializerFactoryImpl;
import org.example.demo.service.IConsumerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@EnableRabbit
@Configuration
public class RabbitmqConfig {
    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitmqConfig.class);

    @Autowired
    private IConsumerService consumerService;

    @RabbitHandler
    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(value = "${spring.rabbitmq.config.exchange}", type = "topic", ignoreDeclarationExceptions = "true"),
                    value = @Queue(value = "${spring.rabbitmq.config.queue.test}", durable = "true"),
                    key = "${spring.rabbitmq.config.routing-key.test}"
            )
    })
    public void onDemoMessageReceived(Message message, Channel channel) {
        org.example.demo.domain.Message msg = this.buildMessage(message);
        long deliveryTag = msg.getDelayMills();
        this.consumerService.consume(msg);
        try {
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
    }

    private org.example.demo.domain.Message buildMessage(Message message) {
        String body = new String(message.getBody());
        LOGGER.info("received message: {}", body);
        Serializer sf = SerializerFactoryImpl.getInstance().create(SerializerVariety.JSON, org.example.demo.domain.Message.class);
        return sf.deserialize(body);
    }
}
